import { observable, action } from 'mobx';
import router from '@/router/index';
import store from './Index';

export default class LoaderStore {
    @observable public isLoading = false;

    @action
    public async run(
        callback: () => void,
        errorCallback: (error: any) => void = () => {},
    ) {
        this.isLoading = true;
        try {
            await callback();
        } catch (error) {
            if (error.message.includes('401')) {
                store.auth.forceLogout();
                store.alert.show('You are logged in another device, redirect to login page', 'error');
                router.replace('/login');
            } else {
                store.alert.show(error.message, 'error');
                await errorCallback(error);
            }
        }
        this.isLoading = false;
    }
}
